<%@ page contentType="text/html; charset=UTF-8" %>
<%@include file="/WEB-INF/views/init.jsp"%>
<%--@elvariable id="price" type="java.lang.Integer"--%>
<%--@elvariable id="minCargoParameters" type="su.samcom.calc.service.util.CargoParameters"--%>
<%--@elvariable id="countries" type="java.util.List<su.samcom.calc.model.entity.Country>"--%>

<script type="text/javascript">
    $.widget( "custom.catcomplete", $.ui.autocomplete, {
        _renderMenu: function( ul, items ) {
            var that = this,
                    currentCategory = "";
            $.each( items, function( index, item ) {
                if ( item.category != currentCategory ) {
                    ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                    currentCategory = item.category;
                }
                that._renderItemData( ul, item );
            });
        }
    });

    var selectlocationFrom = function(event, ui){
        $("#locationFrom").attr("placeholder", ui.item.label);
        //$("input[name=locationFromId]").val(ui.item.id);
    }

    var selectlocationTo = function(event, ui){
        $("#locationTo").attr("placeholder", ui.item.label);
        //$("input[name=locationToId]").val(ui.item.id);
    }

    var sourceLocation = function( request, response, countryId) {
        $.ajax({
            url: "<spring:url value="/calculator/locations"/>",
            dataType: "json",
            async: false,
            type: "POST",
            data: {
                locationName: request.term,
                countryId: countryId
            },
            success: function(data){
                response(data);
            }
        });
    }

    var sourcelocationFrom = function(request, response){
        var countryId = $("input[name=countryFromId]:checked").val();
        sourceLocation(request, response, countryId);
    }

    var sourcelocationTo = function(request, response){
        var countryId = $("input[name=countryToId]:checked").val();
        sourceLocation(request, response, countryId);
    }

    $(document).ready(function(){


        $( "#countryFromId" ).buttonset();
        $( "input[name=countryFromId]" ).change(function(){
            $( "#locationFrom" ).removeAttr("disabled");
        });
        $( "#countryToId" ).buttonset();
        $( "input[name=countryToId]" ).change(function(){
            $( "#locationTo" ).removeAttr("disabled");
        });
        $( "#cargoType" ).buttonset();
        $( "input[name=cargoType]" ).change(function(){
            $.ajax({
                url: '<spring:url value="/calculator/cargo-parameters"/>',
                type: 'post',
                data: {
                    cargoType: $('input[name=cargoType]:checked').val()
                },
                success: function(cargoParameters){
                    $( "#cbmHeader" ).text('Объем (минимум ' + cargoParameters.cbm + ' кубов)');
                    $( "#lengthHeader" ).text('Длина по фуре (минимум ' + cargoParameters.length + ' метров)');
                    $( "#weightHeader" ).text('Вес (минимум ' + cargoParameters.weight + ' тонн)');
                }

            });
        });

        $("#locationFrom").catcomplete({
            source: sourcelocationFrom
        });

        $("#locationTo").catcomplete({
            source: sourcelocationTo
        });

        $("input[type=button]").button();

//        $("input[placeholder]").placeholder();


        /*$("input[name=cbm]:first").keyfilter(/\d/);
         $("input[name=length]:first").keyfilter(/\d/);
         $("input[name=weight]:first").keyfilter(/\d/);*/

    });

    ajaxSubmitPriceForm = function(){
        $.ajax({
            type: 'post',
            url: '<spring:url value="/calculator/calculate"/>',
            data: $("#calculatorForm").serialize(),
            success: function(response){
                $("#parentCalculatorForm").html(response);
            }
        });
    }

</script>

<spring:url var="action" value="/calculator/calculate"/>
<form:form modelAttribute="calculatorForm" method="POST" action="${action}">
    <div class="location">
        <h4>Пункт отправки</h4>
        <div id="countryFromId">
            <c:forEach items="${countries}" var="country" varStatus="status">
                <form:radiobutton id="countryFromId${country.id}" path="countryFromId" value="${country.id}"/>
                <label for="countryFromId${country.id}"><c:out value="${country.name}"/></label>
            </c:forEach>
        </div>
        <form:input id="locationFrom" disabled="${empty calculatorForm.countryFromId}" path="locationFrom" type="text" placeholder="Выберите пункт отправки"/>
        <div class="error">${locationFromError}</div>
    </div>
    <div class="location">
        <h4>Пункт назначения</h4>
        <div id="countryToId">
            <c:forEach items="${countries}" var="country">
                <form:radiobutton id="countryToId${country.id}" path="countryToId" value="${country.id}"/>
                <label for="countryToId${country.id}"><c:out value="${country.name}"/></label>
            </c:forEach>
        </div>
        <form:input id="locationTo" disabled="${empty calculatorForm.countryToId}" path="locationTo" placeholder="Выберите пункт назначения"/>
        <div class="error">${locationToError}</div>
    </div>
    <div style="clear: both;"/>
    <h4>Тип груза</h4>
    <div id="cargoType">
        <form:radiobutton id="generalCargo" path="cargoType" value="GENERAL"/>
        <label for="generalCargo">Сборный</label>
        <form:radiobutton id="separateCargo" path="cargoType" value="SEPARATE"/>
        <label for="separateCargo">Отдельный</label>
    </div>
    <div class="error">${cargoTypeError}</div>
    <h4 id="cbmHeader">Объем
        <c:if test="${!empty minCargoParameters}">
            (минимум ${minCargoParameters.cbm} кубов)
        </c:if>
        <c:if test="${empty minCargoParameters}">
            (кубы)
        </c:if>
    </h4>
    <form:input path="cbm" placeholder="Объем (кубы)"/>
    <div class="error">${cbmError}</div>
    <h4 id="lengthHeader">Длина по фуре
        <c:if test="${!empty minCargoParameters}">
            (минимум ${minCargoParameters.length} метров)
        </c:if>
        <c:if test="${empty minCargoParameters}">
            (метры)
        </c:if>
    </h4>
    <form:input path="length" placeholder="Длина по фуре (метры)"/>
    <div class="error">${lengthError}</div>
    <h4  id="weightHeader">Вес
        <c:if test="${!empty minCargoParameters}">
            (минимум ${ minCargoParameters.weight} тонн)
        </c:if>
        <c:if test="${empty minCargoParameters}">
            (тонны)
        </c:if>
    </h4>
    <form:input path="weight" placeholder="Вес (тонны)"/>
    <div class="error">${weightError}</div>
    <input type="button" style="display: block; margin-top: 10px;"  onclick="ajaxSubmitPriceForm()" value="Рассчитать"/>
    <span class="error"><c:out value="${commonError}"/></span>
    <c:if test="${!empty price}">
        <span style="line-height: 40px;">
            <span class="light-text">
                Стоимость доставки составит <span class="normal-text bold"><c:out value="${price}"/></span> руб.
            </span>
        </span>
    </c:if>
</form:form>